<template>
  <body>
    <div>
      <h1 class="complete_user">比赛参与情况</h1>
      <el-table :data="events" border style="width: 89%;margin-left:5%;">
        <el-table-column prop="type" label="类型" width="400"></el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          width="400"
        ></el-table-column>
        <el-table-column prop="time" label="时间" width="400"></el-table-column>
        <el-table-column label="操作" width="400">
          <template slot-scope="scope">
            <el-button
              @click="eventAndPlay_detail(scope.row)"
              type="text"
              size="small"
              >查看</el-button
            >
            <el-button type="text" @click="cancelEvent(scope.row)" size="small"
              >取消报名</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <h1 class="complete_user">活动参与情况</h1>
      <el-table :data="play1" border style="width: 89%;margin-left:5%;">
        <el-table-column prop="type" label="类型" width="400"></el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          width="400"
        ></el-table-column>
        <el-table-column prop="time" label="时间" width="400"></el-table-column>
        <el-table-column label="操作" width="400">
          <template slot-scope="scope">
            <el-button
              @click="eventAndPlay_detail(scope.row)"
              type="text"
              size="small"
              >查看</el-button
            >
            <el-button type="text" @click="cancelPlay(scope.row)" size="small"
              >取消报名</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <h1 class="complete_user">"完善"用户信息</h1>
      <el-form label-width="120px" @submit.native.prevent="save">
        <el-form-item label="用户名">
          <el-input v-model="username.name"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="username.password"></el-input>
        </el-form-item>
        <el-form-item label="QQ号">
          <el-input v-model="username.qqNumber"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="username.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <!-- <el-input v-model="username.avatar"></el-input> -->
          <el-avatar :size="200" :src="username.avatar"></el-avatar>
        </el-form-item>
        <el-form-item label="添加新头像">
          <!--elementui的上传图片的upload组件-->
          <el-upload
            class="upload-demo"
            ref="upload"
            list-type="picture-card"
            action="/api/user"
            :limit="9"
            :before-upload="beforeupload"
            :on-exceed="exceedHandle"
            :auto-upload="false"
            :multiple="true"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="username.telephone"></el-input>
        </el-form-item>
        <el-form-item class="complete_user_save">
          <el-button type="primary" native-type="submit">保存</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-drawer
      :title="title"
      v-if="drawer"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
      size="50%"
    >
      <div
        v-html="body"
        style="height:500px;width:100%;overflow:auto;padding:20px 150px;"
      ></div>
    </el-drawer>
  </body>
</template>
<script>
import axios from "axios";
axios.defaults.withCredentials = true; // 引入axios
export default {
  data() {
    return {
      username: {
        id: "",
        password: "",
        name: "",
        telephone: "",
        qqNumber: "",
        email: ""
      },
      events: [],
      items: [],
      play: [],
      play1: [],
      id: "",
      findFlight: {},
      items_history: [],
      total: 100, //默认数据总数
      pagesize: 9, //每页的数据条数
      currentPage: 1, //默认开始页面
      changes: [],
      param: "",
      param2: "",
      hasImg: false,
      event: {
        registration: {
          eventId: "",
          teamId: ""
        },
        type: 0,
        teams: [
          {
            teamId: "",
            userId: ""
          }
        ]
      },
      palyItem: {
        registerNumber: "",
        eventId: ""
      },

      drawer: false,
      direction: "rtl"
    };
  },
  created() {
    this.fetchName();
    this.fetchEvents();
    this.fetchPlays();
  },
  methods: {
    beforeupload(file) {
      this.hasImg = true;
      this.param = new FormData();
      this.param.append("upload", file);
      return false;
    },
    async save() {
      // if (this.username.telephone == '' || (!(/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/).test(this.username.phone))) {
      //   this.$message({
      //     type: 'error',
      //     message: '手机号格式错误'
      //   })
      //   return
      // }
      if (this.hasImg === false) {
        this.param = new FormData();
      }
      let _this = this;
      _this.$refs.upload.submit();
      if (this.id) {
        this.param.append("_method", "put");
      }
      this.param.append("id", _this.id);
      this.param.append("password", _this.username.password);
      this.param.append("name", _this.username.name);
      this.param.append("telephone", _this.username.telephone);
      this.param.append("qqNumber", _this.username.qqNumber);
      this.param.append("email", _this.username.email);
      // 4.3，然后通过下面的方式把内容通过axios来传到后台
      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: localStorage.token || ""
        }
      };
      global.console.log(this.param);
      axios.post("/api/user", this.param, config).then(function(result) {
        global.console.log(result);
      });

      this.$message({
        type: "success",
        message: "保存成功"
      });
      setTimeout(() => {
        this.fetchName();
      }, 100);
    },
    eventAndPlay_detail(row) {
      global.console.log(row);
      this.drawer = true;
      this.title = row.title;
      this.body = row.content;
    },
    handleClose(done) {
      done();
    },
    //取消比赛报名
    cancelEvent(row) {
      this.$confirm(`此操作将取消报名"${row.title}", 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        // console.log(row)
        // console.log(this.username.id)
        this.event.registration.eventId = row.eventId;
        this.event.registration.teamId = row.teamId;
        this.event.teams[0].teamId = row.teamId;
        this.event.teams[0].userId = this.username.id;
        global.console.log(this.event);
        const res = await this.$http.delete("/takePart", { data: this.event });
        if (res.data.code === 8004) {
          this.$message({
            type: "error",
            message: "取消报名失败"
          });
          return;
        }
        this.$message({
          type: "success",
          message: "取消成功!"
        });
        this.fetchEvents();
      });
    },
    //取消活动报名
    cancelPlay(row) {
      this.$confirm(`此操作将取消报名"${row.title}", 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        let _this = this;
        this.param2 = new FormData();
        this.param2.append("registerNumber", _this.username.id);
        this.param2.append("eventId", row.eventId);
        this.param2.append("_method", "delete");
        let config = {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: localStorage.token || ""
          }
        };
        // this.palyItem.registerNumber=this.username.id;
        // this.palyItem.eventId=row.eventId;
        const res = await axios.post("/api/join", this.param2, config);
        if (res.data.code === 7004) {
          this.$message({
            type: "error",
            message: "取消报名失败"
          });
          return;
        }
        this.$message({
          type: "success",
          message: "取消成功!"
        });
        this.fetchPlays();
      });
    },
    // 5设置超过9张图给与提示
    exceedHandle() {
      alert("您现在选择已超过9张图，请重新选择");
    },
    async fetchEvents() {
      if (this.$cookies.isKey("user_info")) {
        this.id = this.$cookies.get("user_info").id;
        //   console.log(localStorage.token)
        let userId = this.id;
        const res = await this.$http.get(`/takePart?userId=${userId}`);
        this.events = res.data.pageInfo.list;
        this.events.forEach(event => {
          event.time = this.$moment(event.time).format("YYYY-MM-DD HH:mm:ss");
        });
      }
    },
    async fetchPlays() {
      if (this.$cookies.isKey("user_info")) {
        this.id = this.$cookies.get("user_info").id;
        //   console.log(localStorage.token)
        let userId = this.id;
        const res = await this.$http.get(`/join?userId=${userId}`);
        this.play = res.data.pageInfo.list[0];
        // res.data.pageInfo.list.forEach(info => {
        //   this.play=info;
        // });
        // this.play.forEach((info, index) => {
        //   this.play1.push(info.events[index]);
        // });
        if (this.play === undefined) {
          this.play1 = [];
        } else {
          this.play1 = this.play.events;
        }
        this.play1[0].time = this.$moment(this.play1[0].time).format(
          "YYYY-MM-DD HH:mm:ss"
        );
        global.console.log(this.play);
      }
    },
    async fetchName() {
      if (this.$cookies.isKey("user_info")) {
        this.id = this.$cookies.get("user_info").id;
        //   console.log(localStorage.token)
        const res = await this.$http.get("/user/" + this.id);
        this.username = res.data.info;
        this.username.avatar =
          "http://121.199.23.187:8080/static/images/avatar/" +
          this.username.avatar;
      }
    },
    login_over() {
      localStorage.clear();
      this.$router.push("login");
    },
    login() {
      this.$router.push("/login");
    },
    user_info() {
      this.$router.push("/useref");
    },
    onSubmit() {
      global.console.log("submit!");
    }
  }
};
</script>

<style>
@import "../assets/css/index.css";
.reserve_card {
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  padding: 20px 0px;
}
.complete_user {
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  padding: 21px 0px;
}
.complete_user_save {
  margin-left: 475px;
}
</style>
